package lyx.game.control
{
	import flash.events.IEventDispatcher;
	import flash.events.KeyboardEvent;
	
	import lyx.game.control.IKeyControlTarget;
	import lyx.game.utils.KeySetting;
	import lyx.game.utils.KeyState;
	import lyx.utils.log.Logger;
	
	/**
	 * 键盘控制器，接收来自键盘的操作，并进行派发至IKeyControlTarget中去执行对应的动作。
	 */	
	public class KeyBoardController
	{	
		/**
		 *  接收来自KeyBoardController派发的按键消息的IKeyControlTarget对象队列。
		 */		
		private const _control_targets:Array = [];
		
		/**
		 *  按键配置
		 */
		public var key_setting:KeySetting = new KeySetting();
		
		private var _key_state:KeyState = new KeyState();
		
		/**
		 * 向触发对象注册控制器，KeyBoardController将会监听来自
		 * trigger的所有按键动作
		 * @param trigger 按键动作派发者
		 * 
		 */		
		final public function registerController(trigger:IEventDispatcher):void
		{
			Logger.getInstance().debug("Register KeyBoardController");
			
			trigger.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
			trigger.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
		}
		
		public function addTarget(target:IKeyControlTarget):void
		{
			var target_index:int = _control_targets.indexOf(target);
			if(target_index==-1)
			{
				_control_targets.push(target);
			}
		}
		
		public function removeTarget(target:IKeyControlTarget):void
		{
			var target_index:int = _control_targets.indexOf(target);
			if(target_index!=-1)
			{
				_control_targets.splice(target_index,1);
			}
		}
		
		/**
		 * 对KeyBoardEvent.KEY_DOWN事件的处理
		 * @param event
		 * 
		 */		
		protected function keyDownHandler(event:KeyboardEvent):void
		{
			if(key_setting.isValidKeyInSetting(event.keyCode))
			{
				if(!_key_state.isKeyPressing(event.keyCode))
				{
					_key_state.addKeyForKeyDown(event.keyCode);
					for each(var target:IKeyControlTarget in _control_targets)
					{
						target.actionByKeysState(_key_state,key_setting);
					}
					Logger.getInstance().debug("Player press key: {0}",event.keyCode);
				}
			}
		}
		
		/**
		 * 对KeyBoardEvent.KEY_UP事件的处理
		 * @param event
		 * 
		 */		
		protected function keyUpHandler(event:KeyboardEvent):void
		{
			if(key_setting.isValidKeyInSetting(event.keyCode))
			{
				_key_state.deleteKeyForKeyUp(event.keyCode);
				for each(var target:IKeyControlTarget in _control_targets)
				{
					target.actionByKeysState(_key_state,key_setting);
				}
			}
		}

	}
}